package dao

import "aglaia/internal/model"

func (d *Dao) Articles(limit, offset int) ([]model.Article, int, error) {
	article := model.Article{}

	articles, total, err := article.List(d.engine, limit, offset)
	if err != nil {
		return nil, 0, err
	}
	// 查询标签 （tag） ,放入 Tags
	for i, v := range articles {
		tag := model.ArticleTag{Model: model.Model{Id: v.Id}}

		articleTags, err := tag.QueryByArticleId(d.engine)
		if err != nil {
			return nil, 0, err
		}
		articles[i].Tags = articleTags
	}

	return articles, total, nil
}

func (d *Dao) QueryArticleById(id uint) (model.ArticleContent, error) {
	article := model.ArticleContent{Model: model.Model{Id: id}}
	if err := article.QueryById(d.engine); err != nil {
		return model.ArticleContent{}, err
	}
	return article, nil
}

func (d *Dao) SearchArticle(data string) ([]model.Article, error) {
	article := model.Article{}
	return article.Search(d.engine, data)
}

func (d *Dao) CreateArticle(title, desc, coverImageUrl, content string, authId, categoryId uint, tagIds []uint) error {
	article := model.Article{
		Title:         title,
		Desc:          desc,
		CoverImageUrl: coverImageUrl,
		Content:       content,
		State:         1,
		AuthId:        authId,
		CategoryId:    categoryId,
	}

	tx := d.engine.Begin()

	if err := article.Create(tx); err != nil {
		tx.Rollback()
		return err
	}

	ids := make(map[uint]struct{})
	for _, v := range tagIds {
		if _, ok := ids[v]; ok {
			continue
		}
		ids[v] = struct{}{}
		articleTag := model.ArticleTag{
			ArticleId: article.Id,
			TagId:     v,
		}
		if err := articleTag.Create(tx); err != nil {
			tx.Rollback()
			return err
		}
	}

	if err := tx.Commit().Error; err != nil {
		tx.Rollback()
		return err
	}

	return nil
}

func (d *Dao) UpdateArticle(id, categoryId uint, title, desc, coverImageUrl, content string, state uint8) error {
	article := model.Article{Model: model.Model{Id: id}}
	values := make(map[string]interface{})
	if title != "" {
		values["title"] = title
	}
	if desc != "" {
		values["desc"] = desc
	}
	if coverImageUrl != "" {
		values["cover_image_url"] = coverImageUrl
	}
	if content != "" {
		values["content"] = content
	}

	values["state"] = state

	if categoryId != 0 {
		values["category_id"] = categoryId
	}
	return article.Update(d.engine, values)
}

func (d *Dao) DeleteArticle(id uint) error {
	article := model.Article{Model: model.Model{Id: id}}
	return article.Delete(d.engine)
}
